package com.github.wujichen158.andemusic.eventsetting;

import com.github.wujichen158.andemusic.lib.Reference;
import com.github.wujichen158.andemusic.network.AndeMusicNetwork;
import com.github.wujichen158.andemusic.network.MusicMessage;
import com.github.wujichen158.andemusic.playernbt.MusicCapability;
import com.github.wujichen158.andemusic.playernbt.MusicTypeProvider;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.event.AttachCapabilitiesEvent;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;

import java.util.Optional;

public class SendPackageEvent {
    @SubscribeEvent
    public void onClonePlayer(PlayerEvent.Clone event) {
        if (event.isWasDeath()) {
            EntityPlayer player = event.getEntityPlayer();
            if (player instanceof EntityPlayerMP) {
                EntityPlayerMP playerMP = (EntityPlayerMP) player;
                Optional.ofNullable(MusicTypeProvider.get(playerMP)).ifPresent(capability -> {
                    Optional.ofNullable(MusicTypeProvider.get(event.getOriginal())).ifPresent(capabilityOri -> {
                        capability.loadNBTData(capabilityOri.saveNBTData());
                        AndeMusicNetwork.INSTANCE.sendTo(new MusicMessage(capability.getMusicType(),
                                capability.getMinDelayTime(), capability.getMaxDelayTime()), playerMP);
                    });
                });
            }
        }
    }

    @SubscribeEvent
    public void entityJoinWorld(EntityJoinWorldEvent event) {
        Entity entity = event.getEntity();
        if (entity instanceof EntityPlayerMP && !entity.world.isRemote) {
            EntityPlayerMP playerMP = (EntityPlayerMP) entity;
            Optional.ofNullable(MusicTypeProvider.get(playerMP)).ifPresent(capability -> {
                AndeMusicNetwork.INSTANCE.sendTo(new MusicMessage(capability.getMusicType(),
                        capability.getMinDelayTime(), capability.getMaxDelayTime()), playerMP);
            });
        }
    }

    @SubscribeEvent
    public void attachCapability(AttachCapabilitiesEvent<Entity> event) {
        Entity entity = event.getObject();
        if (entity instanceof EntityPlayer) {
            EntityPlayer player = (EntityPlayer) entity;
            if (!player.hasCapability(MusicTypeProvider.CAP, null)) {
                event.addCapability(new ResourceLocation(Reference.MOD_ID),
                        new MusicTypeProvider(new MusicCapability()));
            }
        }
    }
}